package org.black.phoneUtility.sms.reply.widget;

import java.util.Date;

import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.reply.provider.SmsReplyContract;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract.PhoneLookup;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class SmsReplyReplyHistoryCursorAdapter extends CursorAdapter {
	private static final String LOG_TAG = SmsReplyReplyHistoryCursorAdapter.class
			.getName();

	final static class ViewHolder {
		TextView toTextView;
		TextView dateTimeTextView;
		TextView messageTextView;
		TextView sourceFromTextView;
	}

	private Context context;
	private LayoutInflater layoutInflater;
	private LruCache<String, String> nameyCache;

	private class PhoneLookupAsyncTask extends AsyncTask<Void, Void, String> {
		private TextView textView;
		private String phoneNumber;

		public PhoneLookupAsyncTask(TextView textView, String phoneNumber) {
			this.textView = textView;
			this.phoneNumber = phoneNumber;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (TextUtils.isEmpty(result) == false) {
				textView.setText(result + " ( " + this.phoneNumber + " )");
			} else {
				textView.setText(phoneNumber);
			}
		}

		@Override
		protected String doInBackground(Void... params) {
			if (TextUtils.isEmpty(phoneNumber) == false) {
				synchronized (nameyCache) {
					if (nameyCache.get(phoneNumber) == null) {
						Cursor contactCursor = null;
						try {
							Uri phoneLookupUri = Uri.withAppendedPath(
									PhoneLookup.CONTENT_FILTER_URI,
									Uri.encode(phoneNumber));
							contactCursor = context.getContentResolver().query(
									phoneLookupUri,
									new String[] { PhoneLookup.DISPLAY_NAME },
									null, null, null);
							if (contactCursor != null
									&& contactCursor.moveToFirst() == true) {
								String displayName = contactCursor.getString(0);
								nameyCache.put(phoneNumber, displayName);
								return displayName;
							} else {
								return null;
							}
						} finally {
							if (contactCursor != null) {
								try {
									contactCursor.close();
								} catch (Throwable throwable) {
									Log.e(LOG_TAG, "Fail to close Cursor",
											throwable);
								}
							}
						}
					} else {
						return nameyCache.get(phoneNumber);
					}
				}
			}
			return null;
		}
	}

	public SmsReplyReplyHistoryCursorAdapter(Context context, Cursor cursor,
			int flag) {
		super(context, cursor, flag);
		this.context = context;
		this.layoutInflater = LayoutInflater.from(this.context);
		this.nameyCache = new LruCache<String, String>(1024);
	}

	@Override
	public void bindView(View view, Context context, final Cursor cursor) {
		ViewHolder viewHolder = (ViewHolder) view.getTag();
		viewHolder.toTextView.setText(cursor.getString(cursor
				.getColumnIndex(SmsReplyContract.ReplyHistories.PHONE_NUMBER)));
		new PhoneLookupAsyncTask(viewHolder.toTextView, cursor.getString(cursor
				.getColumnIndex(SmsReplyContract.ReplyHistories.PHONE_NUMBER)))
				.execute();
		Date sendDateTime = new Date(
				cursor.getLong(cursor
						.getColumnIndex(SmsReplyContract.ReplyHistories.CREATION_DATE_TIME)));

		viewHolder.dateTimeTextView.setText(DateFormat.getDateFormat(context)
				.format(sendDateTime)
				+ " "
				+ DateFormat.getTimeFormat(context).format(sendDateTime));
		viewHolder.messageTextView
				.setText(cursor.getString(cursor
						.getColumnIndex(SmsReplyContract.ReplyHistories.REPLY_MESSAGE)));
		int sourceFrom = cursor.getInt(cursor
				.getColumnIndex(SmsReplyContract.ReplyHistories.SOURCE_FROM));
		if (sourceFrom == SmsReplyContract.ReplyHistories.REPLY_HISTORY_SOURCE_FROM_VALUE_PHONE) {
			viewHolder.sourceFromTextView
					.setText(context
							.getString(R.string.sms_reply_reply_history_source_missed_call));
		} else if (sourceFrom == SmsReplyContract.ReplyHistories.REPLY_HISTORY_SOURCE_FROM_VALUE_SMS) {
			viewHolder.sourceFromTextView.setText(context
					.getString(R.string.sms_reply_reply_history_source_sms));
		} else {
			Log.e(LOG_TAG, "source_from does not match type. sourceFrom: "
					+ sourceFrom);
		}
	}

	@Override
	public View newView(Context context, final Cursor cursor, ViewGroup parent) {
		View result = this.layoutInflater.inflate(
				R.layout.sms_reply_history_list_row, parent, false);
		ViewHolder viewHolder = new ViewHolder();
		viewHolder.toTextView = (TextView) result
				.findViewById(R.id.smsReplyHistoryListRowToTextView);
		viewHolder.dateTimeTextView = (TextView) result
				.findViewById(R.id.smsReplyHistoryListRowDateTimeTextView);
		viewHolder.messageTextView = (TextView) result
				.findViewById(R.id.smsReplyHistoryListRowMessageTextView);
		viewHolder.sourceFromTextView = (TextView) result
				.findViewById(R.id.smsReplyHistoryListRowSoruceFromTextView);
		result.setTag(viewHolder);
		return result;
	}
}
